import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Select, Popconfirm } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import styles from '../../../global.less';
import { queryRule, updateRule, addRule, removeRule, getStoreList } from './service';
import FormItem from 'antd/lib/form/FormItem';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    console.log(error);
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const { Option } = Select;
const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [,] = useState();
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const [storeList, setSoreList] = useState([]);
  const [StoreValue, setStoreValue] = useState({});
  const [count, setCount] = useState(0);
  const [status, setStatus] = useState(0);
  const handleState = (e) => {
    setStatus(e);
  };
  const handStore = (params) => {
    getStoreList(params).then((res) => {
      const { code, data } = res;
      code === 0 ? setSoreList(data) : null;
    });
  };
  const handleSearch = (value) => {
    if (value) {
      handStore({ name: value });
    } else {
      setSoreList([]);
    }
  };
  const handleChange = (value, e) => {
    const list = {
      name: e.children,
      id: value,
    };
    setStoreValue(list);
  };
  const columns = [
    {
      title: '工号',
      dataIndex: 'number',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '姓名为必填项',
          },
        ],
      },
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },

    {
      title: '店铺名',
      dataIndex: 'storeName',
      render: (_, record) => {
        return <span>{record.storeName}</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem name="storeName" label={null} className="formItem_div">
            <Select
              showSearch
              value={StoreValue ? StoreValue.id : null}
              placeholder="请输入店铺"
              defaultActiveFirstOption={false}
              showArrow={false}
              filterOption={false}
              onSearch={handleSearch}
              onChange={handleChange}
              notFoundContent={null}
            >
              {storeList.map((item, index) => {
                return (
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                );
              })}
            </Select>
          </FormItem>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '店铺为必填项',
          },
        ],
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '启用',
          status: 'Processing',
        },
        1: {
          text: '关闭',
          status: 'Error',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择状态" value={status} onChange={handleState}>
            <Option value={0}>启用</Option>
            <Option value={1}>关闭</Option>
          </Select>
        );
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                handleModalVisible(true);
                setStepFormValues(record);
                const list = {
                  id: record.storeId,
                  name: record.storeName,
                };
                setStoreValue(list);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
            <Popconfirm
              title="确定删除用户吗?"
              onConfirm={() => {
                handleRemove(record.id, actionRef);
              }}
              okText="是"
              cancelText="否"
            >
              <a>删除</a>
            </Popconfirm>
          </>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="经销商列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{x:1200}}
        bordered
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setStepFormValues();
              setStoreValue();
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total);
          return list||[];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />

      <CreateForm
        title={stepFormValues ? '修改商户' : '新增商户'}
        width={800}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            if (StoreValue && StoreValue.id) {
              value.status = status;
              value.storeId = StoreValue.id;
              value.storeName = StoreValue.name;
              stepFormValues ? (value.id = stepFormValues.id) : null;
              const success = stepFormValues ? await handleUpdate(value) : await handleAdd(value);
              if (success) {
                handleModalVisible(false);

                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            } else {
              message.error('请输入正确的店铺');
            }
          }}
          form={{
            initialValues: stepFormValues ? stepFormValues : null,
            layout: 'horizontal',
            labelAlign: 'rihgt',
            labelCol: { span: 7 },
            wrapperCol: { span: 20 },
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
